// 邮箱账户管理模块
const EmailAccountManager = {
    // 加载指定账户的文件夹列表并刷新
    refreshAccountFolders: async function(accountId, folderToSelect, triggerElement) {
        const $trigger = $(triggerElement);
        const $icon = $trigger ? $trigger.find('.layui-icon') : null;
        
        // 防止重复点击
        if ($trigger && $trigger.hasClass('refreshing')) {
            return;
        }
        
        if ($trigger && $icon) {
            $trigger.addClass('refreshing');
            $icon.addClass('layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop');
        }
        
        try {
            // 手动刷新时强制同步，从服务器获取最新文件夹列表
            const folders = await Api.apiRequest(`/email-accounts/${accountId}/folders?force_sync=true`);
            
            // 找到对应的账户项
            const $accountItem = $(`.account-list-item[data-account-id="${accountId}"]`);
            const $folderContainer = $accountItem.find('.account-folder-dl');
            
            // 记录当前展开的文件夹
            const expandedFolders = [];
            $folderContainer.find('.folder-toggle-icon.layui-icon-down').each(function() {
                const folderName = $(this).closest('.folder-item-container').find('.folder-link').data('folder-name');
                expandedFolders.push(folderName);
            });
            
            // 重新渲染文件夹
            const foldersHtml = App.renderFolders(folders, accountId);
            $folderContainer.html(foldersHtml);
            
            // 恢复之前展开的文件夹状态
            expandedFolders.forEach(folderName => {
                const $folderLink = $folderContainer.find(`.folder-link[data-folder-name="${folderName}"]`);
                if ($folderLink.length) {
                    const $container = $folderLink.closest('.folder-item-container');
                    $container.find('.folder-toggle-icon')
                        .removeClass('layui-icon-right')
                        .addClass('layui-icon-down');
                    $folderLink.closest('dd').find('.sub-folder-dl').first().show();
                }
            });
            
            // 恢复所有徽标
            App.updateAllUnreadBadges();
            
            // 重新绑定事件
            App.bindFolderEvents();
            
            // 如果指定了要选中的文件夹，则恢复选中状态
            if (folderToSelect) {
                const targetFolderLink = $folderContainer.find(`a.folder-link[data-folder-name='${folderToSelect}']`);
                if (targetFolderLink.length > 0) {
                    targetFolderLink.closest('dd.folder-item').addClass('selected');
                }
            }

            if (triggerElement) {
                layui.layer.msg('文件夹列表已刷新', { icon: 1, time: 1000 });
            }

        } catch (error) {
            console.error('刷新文件夹列表失败:', error);
            layui.layer.msg('刷新失败: ' + (error.detail || error.message), { icon: 2 });
        } finally {
            // 移除加载状态
            if ($trigger && $icon) {
                setTimeout(() => {
                    $trigger.removeClass('refreshing');
                    $icon.removeClass('layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop');
                }, 500);
            }
        }
    },

    // 显示账户设置菜单
    showAccountSettings: function(accountId, triggerElement) {
        const $accountItem = $(triggerElement).closest('.account-list-item');
        const wasSelected = $accountItem.hasClass('selected');
        
        // 在打开菜单前立即添加选中状态（如果之前是选中的）
        if (wasSelected) {
            $accountItem.addClass('selected');
        }
        
        layui.dropdown.render({
            elem: triggerElement,
            show: true,
            data: [
                { title: '复制邮箱', id: 'copy' },
                { type: '-' },
                { title: '刷新文件夹', id: 'refresh' },
                { title: '创建文件夹', id: 'create_folder' },
                { title: '同步邮件', id: 'sync' },
                { type: '-' },
                { title: '修改配置', id: 'edit' },
                { title: '重命名', id: 'rename' },
                { type: '-' },
                { title: '删除邮箱', id: 'delete' }
            ],
            click: function(data) {
                switch (data.id) {
                    case 'refresh':
                        EmailAccountManager.refreshAccountFolders(accountId, null, triggerElement);
                        break;
                    case 'edit':
                        AccountModule.editAccountConfig(accountId);
                        break;
                    case 'sync':
                        AccountModule.syncAccount(accountId);
                        break;
                    case 'rename':
                        AccountModule.renameAccount(accountId);
                        break;
                    case 'create_folder':
                        AccountModule.createFolder(accountId);
                        break;
                    case 'copy':
                        AccountModule.copyEmailAddress(accountId);
                        break;
                    case 'delete':
                        AccountModule.deleteAccount(accountId);
                        break;
                }
            },
            ready: function() {
                // 菜单打开后，强制确保账户保持选中状态
                if (wasSelected) {
                    // 使用 setTimeout 确保在 layui 的内部处理之后执行
                    setTimeout(() => {
                        $accountItem.addClass('selected');
                    }, 0);
                }
            },
            // 菜单关闭时的回调
            done: function() {
                // 菜单关闭后，如果之前是选中的，确保选中状态保持
                if (wasSelected) {
                    $accountItem.addClass('selected');
                }
                // 无论如何关闭（点击项或外部），都清空标记
                App.config.currentOpenMenuAccountId = null;
            }
        });
    },

    // 显示自定义文件夹的设置菜单
    showFolderSettings: function(element, accountId, folderName) {
        layui.dropdown.render({
            elem: element,
            show: true,
            data: [
                { title: '添加子文件夹', id: 'add' },
                { title: '重命名', id: 'rename' },
                { title: '删除', id: 'delete' }
            ],
            click: function(data) {
                switch (data.id) {
                    case 'add':
                        AccountModule.createFolder(accountId, folderName);
                        break;
                    case 'rename':
                        AccountModule.renameFolder(accountId, folderName);
                        break;
                    case 'delete':
                        EmailAccountManager.deleteFolder(accountId, folderName);
                        break;
                }
            },
            // 确保菜单在触摸设备上也能正常显示
            trigger: App.config.isTouchDevice ? 'click' : 'hover',
            done: function() {
                // 菜单关闭后不需要执行任何特殊操作，但保留done回调是好的实践
            }
        });
    },

    // 删除文件夹
    deleteFolder: async function(accountId, folderName) {
        const folderLink = $(`.folder-link[data-account-id="${accountId}"][data-folder-name="${folderName}"]`);
        const wasSelected = folderLink.closest('.folder-item').hasClass('selected');

        layer.confirm('确定要删除该文件夹吗？此操作不可恢复。', {
            title: '确认删除',
            icon: 3
        }, async (index) => {
            try {
                await Api.apiRequest(`/email-accounts/${accountId}/folders`, {
                    method: 'DELETE',
                    body: JSON.stringify({ folder_name: String(folderName) })
                });
                layer.close(index);
                layer.msg('文件夹删除成功', { icon: 1 });

                // 如果删除的是当前选中的文件夹，则刷新后选中INBOX
                const folderToSelectAfterDelete = wasSelected ? 'INBOX' : null;
                this.refreshAccountFolders(accountId, folderToSelectAfterDelete, null);
                
                // 通过WebSocket请求后端刷新未读数
                if (App.ws && App.ws.readyState === WebSocket.OPEN) {
                    App.ws.send(JSON.stringify({
                        action: 'refresh_unread_counts'
                    }));
                    console.log('已发送未读数刷新请求');
                }
            } catch (error) {
                console.error('删除文件夹失败:', error);
                layer.msg(error.message || '删除文件夹失败', { icon: 2 });
            }
        });
    }
};